package yazan.com.pdacollector_android.activity;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.maning.mndialoglibrary.MProgressDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yazan.com.pdacollector_android.R;
import yazan.com.pdacollector_android.adapter.OrderBrowserAdapter;
import yazan.com.pdacollector_android.base.BaseActivity;
import yazan.com.pdacollector_android.base.Presenter;
import yazan.com.pdacollector_android.model.OrderBrowser;
import yazan.com.pdacollector_android.model.OrderBrowserInfo;
import yazan.com.pdacollector_android.model.OrderInfo;
import yazan.com.pdacollector_android.presenter.OrderPresenter;
import yazan.com.pdacollector_android.utils.MProgressDialogHelper;
import yazan.com.pdacollector_android.utils.PDAGlobal;

public class OrderBrowserActivity extends BaseActivity {

    //<editor-fold desc=”成员变量”>


    @BindView(R.id.spType)
    Spinner spType;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.btDelete)
    Button btDelete;
    @BindView(R.id.btValidation)
    Button btValidation;
    @BindView(R.id.tvBegin)
    TextView tvBegin;
    @BindView(R.id.tvEnd)
    TextView tvEnd;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.vgBottomOperator)
    ConstraintLayout vgBottomOperator;
    @BindView(R.id.etUnique)
    EditText etUnique;

    private OrderBrowserAdapter orderBrowserAdapter;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    private int pageIndex = 0;

    private int spSelect = 0;

    private List<OrderInfo> mOrderInfoList;

    //</editor-fold>


    //<editor-fold desc=”生命周期”>


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_broswer);
        ButterKnife.bind(this);

        configUI();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PDAGlobal.selectPositionForBrowser = -1;
    }

    //</editor-fold>


    //<editor-fold desc=”私有方法”>


    private void configUI() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        orderBrowserAdapter = new OrderBrowserAdapter(R.layout.item_order_browser, null, this);
        orderBrowserAdapter.bindToRecyclerView(recyclerView);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        orderBrowserAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (PDAGlobal.selectPositionForBrowser != -1) {
                    View child = adapter.getViewByPosition(PDAGlobal.selectPositionForBrowser, R.id.tvIndex);
                    if (child == null) {
                        return;
                    }
                    View oldSelectionView = (View) child.getParent();
                    OrderBrowserInfo item = (OrderBrowserInfo) adapter.getItem(PDAGlobal.selectPositionForBrowser);
                    if (item != null) {
                        if (item.getForder_status() == 2) {
                            oldSelectionView.setBackgroundColor(getResources().getColor(R.color.darkgray));
                        } else {
                            oldSelectionView.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                        }
                    }
                    if (position == PDAGlobal.selectPositionForBrowser) {
                        PDAGlobal.selectPositionForBrowser = -1;
                        return;
                    }
                }

                PDAGlobal.selectPositionForBrowser = position;
                view.setBackgroundColor(getResources().getColor(R.color.colorRed));
            }
        });

        smartRefreshLayout.setEnableRefresh(false);
        smartRefreshLayout.setEnableLoadMore(false);
        smartRefreshLayout.setDisableContentWhenLoading(true);
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                queryFromNetWork();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            }
        });


        tvBegin.setText(TimeUtils.date2String(new Date(), dateFormat));
        tvEnd.setText(TimeUtils.date2String(new Date(), dateFormat));

        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                spSelect = i;
                if (i == 2) {
                    vgBottomOperator.setVisibility(View.VISIBLE);
                } else {
                    vgBottomOperator.setVisibility(View.GONE);
                }
                resetData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void resetData() {
        smartRefreshLayout.setNoMoreData(false);
        orderBrowserAdapter.setNewData(null);
        pageIndex = 0;
        PDAGlobal.selectPositionForBrowser = -1;
    }


    @OnClick({R.id.btQuery, R.id.btDelete, R.id.btValidation, R.id.tvBegin, R.id.tvEnd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btQuery:
                Date begin = TimeUtils.string2Date(tvBegin.getText().toString(), dateFormat);
                Date end = TimeUtils.string2Date(tvEnd.getText().toString(), dateFormat);
                if (begin.after(end)) {
                    ToastUtils.showShort("开始时间不能大于结束时间!");
                    return;
                }
                MProgressDialogHelper.showLoading(this);
                resetData();
                queryFromDBorNetWork();
                break;
            case R.id.btDelete: {
                if (PDAGlobal.selectPositionForBrowser == -1) {
                    return;
                }
                OrderBrowserInfo orderBrowserAdapterItem = orderBrowserAdapter.getItem(PDAGlobal.selectPositionForBrowser);
                if (orderBrowserAdapterItem != null) {
                    deleteOrderInfoFromDB(orderBrowserAdapterItem.getForder_id());
                }
            }
            break;
            case R.id.btValidation: {
                if (PDAGlobal.selectPositionForBrowser == -1) {
                    return;
                }
                OrderBrowserInfo orderBrowserAdapterItem = orderBrowserAdapter.getItem(PDAGlobal.selectPositionForBrowser);
                if (orderBrowserAdapterItem != null) {
                    Intent intent = new Intent(this, OrderDetailActivity.class);
                    intent.putExtra("Forder_id", orderBrowserAdapterItem.getForder_id());
                    startActivity(intent);
                }
            }
            break;
            case R.id.tvBegin: {
                Calendar c = Calendar.getInstance();
                int mYear = c.get(Calendar.YEAR);
                int mMonth = c.get(Calendar.MONTH);
                int mDay = c.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        StringBuffer sb = new StringBuffer();
                        sb.append(i);
                        sb.append("-");
                        sb.append(i1 + 1);
                        sb.append("-");
                        sb.append(i2);
                        tvBegin.setText(sb);
                    }
                }, mYear, mMonth, mDay);
                datePickerDialog.show();
            }
            break;
            case R.id.tvEnd: {
                Calendar c = Calendar.getInstance();
                int mYear = c.get(Calendar.YEAR);
                int mMonth = c.get(Calendar.MONTH);
                int mDay = c.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        StringBuffer sb = new StringBuffer();
                        sb.append(i);
                        sb.append("-");
                        sb.append(i1 + 1);
                        sb.append("-");
                        sb.append(i2);
                        tvEnd.setText(sb);
                    }
                }, mYear, mMonth, mDay);
                datePickerDialog.show();
            }
            break;
        }
    }


    private void queryFromDBorNetWork() {
        MProgressDialogHelper.showLoading(this);
        if (spSelect == 2) {
            queryFromDB();
        } else {
            queryFromNetWork();
        }
    }

    private void deleteOrderInfoFromDB(long Forder_id) {
        OrderInfo orderInfo = mOrderInfoList.get(PDAGlobal.selectPositionForBrowser);
        OrderPresenter.deleteOrderInfo(Forder_id, orderInfo.getData(), new DeleteOrderInfoFromDBListener(this));
    }

    private void queryFromDB() {
        OrderPresenter.searchOrderInfo(tvBegin.getText().toString(), tvEnd.getText().toString(),
                etUnique.getText().toString(), new QueryFromDBListener(this));
    }

    private void queryFromNetWork() {
        Long uniqueCode = null;
        String uniqueCodeStr = etUnique.getText().toString();
        if (RegexUtils.isMatch("^[\\d]*$", uniqueCodeStr)) {
            uniqueCode = Long.parseLong(uniqueCodeStr);
        }

        OrderPresenter.getOrderBrowser(tvBegin.getText().toString(), tvEnd.getText().toString(), SPUtils.getInstance().getString("username"),
                spSelect + 1, pageIndex, uniqueCode, new QueryFromNetWorkListener(this));
    }


    //</editor-fold>

    //<editor-fold desc=”内部类”>
    private static class DeleteOrderInfoFromDBListener implements Presenter.PresenterListener<Boolean> {
        private WeakReference<OrderBrowserActivity> weakReference;

        public DeleteOrderInfoFromDBListener(OrderBrowserActivity context) {
            weakReference = new WeakReference<>(context);
        }

        @Override
        public void onSuccess(Boolean object) {
            if (!object || weakReference.get() == null) {
                return;
            }

            OrderBrowserActivity orderBrowserActivity = weakReference.get();
            orderBrowserActivity.orderBrowserAdapter.remove(PDAGlobal.selectPositionForBrowser);
            PDAGlobal.selectPositionForBrowser = -1;
            orderBrowserActivity.smartRefreshLayout.finishLoadMoreWithNoMoreData();
        }

        @Override
        public void onError(String error) {

        }
    }

    private static class QueryFromDBListener implements Presenter.PresenterListener<List<OrderInfo>> {
        private WeakReference<OrderBrowserActivity> weakReference;

        public QueryFromDBListener(OrderBrowserActivity context) {
            weakReference = new WeakReference<>(context);
        }

        @Override
        public void onSuccess(List<OrderInfo> object) {
            MProgressDialog.dismissProgress();

            OrderBrowserActivity orderBrowserActivity = weakReference.get();

            if (orderBrowserActivity == null) {
                return;
            }

            orderBrowserActivity.mOrderInfoList = object;

            if (object != null && object.size() != 0) {
                List<OrderBrowserInfo> orderBrowserInfoList = new ArrayList<>();
                for (OrderInfo orderInfo : object) {
                    OrderBrowserInfo orderBrowserInfo = new OrderBrowserInfo();
                    orderBrowserInfo.setForder_id(orderInfo.getForder_id());
                    orderBrowserInfo.setForder_sn(orderInfo.getForder_sn());
                    orderBrowserInfo.setForder_date(orderInfo.getForder_date());
                    orderBrowserInfo.setForder_status(3);
                    orderBrowserInfo.setFexa_date(orderInfo.getFexa_date());
                    orderBrowserInfoList.add(orderBrowserInfo);
                }

                orderBrowserActivity.orderBrowserAdapter.addData(orderBrowserInfoList);
                orderBrowserActivity.smartRefreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                ToastUtils.showShort("无数据");
            }
        }

        @Override
        public void onError(String error) {
            MProgressDialog.dismissProgress();
        }
    }

    private static class QueryFromNetWorkListener implements Presenter.PresenterListener<OrderBrowser> {
        private WeakReference<OrderBrowserActivity> weakReference;

        public QueryFromNetWorkListener(OrderBrowserActivity context) {
            weakReference = new WeakReference<>(context);
        }

        @Override
        public void onSuccess(OrderBrowser object) {
            MProgressDialog.dismissProgress();

            if (weakReference.get() == null) {
                return;
            }

            OrderBrowserActivity orderBrowserActivity = weakReference.get();

            if (object == null || object.getData() == null) {
                orderBrowserActivity.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                ToastUtils.showShort("无数据");
                return;
            }

            for (OrderBrowserInfo orderBrowserInfo : object.getData()) {
                orderBrowserInfo.setForder_status(orderBrowserActivity.spSelect + 1);
            }

            if (object.getData().size() != 0) {
                orderBrowserActivity.orderBrowserAdapter.addData(object.getData());
            }
            orderBrowserActivity.smartRefreshLayout.finishLoadMoreWithNoMoreData();

//            if (object.getData().size() < 20) {
//                if (object.getData().size() != 0) {
//                    orderBrowserActivity.orderBrowserAdapter.addData(object.getData());
//                }
//                orderBrowserActivity.smartRefreshLayout.finishLoadMoreWithNoMoreData();
//            } else {
//                orderBrowserActivity.orderBrowserAdapter.addData(object.getData());
//                orderBrowserActivity.smartRefreshLayout.finishLoadMore();
//            }
//            orderBrowserActivity.pageIndex++;
        }

        @Override
        public void onError(String error) {
            MProgressDialog.dismissProgress();
            if (weakReference.get() != null) {
                MProgressDialogHelper.showFail(weakReference.get(), "网络链接异常!", null);
            }
        }
    }

    //</editor-fold>
}
